const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const bodyParser = require('koa-bodyparser');
const routers = require('./api');
const koajwt = require('koa-jwt');
const {jwt: {SECRET, unless}} = require('../config/config.json');
const verirytoken = require('./util/verifytoken');
const logger = require('./middleware/log4.js');
const db = require('./model');
const app = new Koa();
app.use(bodyParser());
app.use(logger());
app.context.db = db;  // 上下文ctx挂载数据库模型，  Redis/Controller 都可以这样挂载
// // 中间件对token进行验证
app.use(async (ctx, next) => {
  const url = ctx.url;
  try {
    // 判断是否需要验证
    if (!unless.some(path => path === url)) {
      let token = ctx.headers.authorization;
      if (token) {
        // 解析jwt信息
        let data = await verirytoken(token, SECRET);
        // 解析成功 上下文添加用户数据
        ctx.state = {
          user: data
        }
      }
    }
    await next();
  } catch (err) {
    console.log(err);
    if (err.status === 401) {
        ctx.status = 401;
        ctx.body = {
            code: 401,
            msg: err.message
        }
    } else {
        throw err;
    }
  }
});
routers(app);
app.use(koajwt({ secret: SECRET, passthrough: true })
  .unless({
    // 登录接口不需要验证
    path: unless.map(path => new RegExp('^' + path))
  })
);
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production';
async function start () {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 8080
  } = nuxt.options.server

  await nuxt.ready()
  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }
  app.use((ctx, next) => {
    let pathName = ctx.request.URL.pathname;
    let ex = /^\/api\//;
    // 如果不是接口请求，渲染页面
    if (!ex.test(pathName)) {
      ctx.status = 200
      ctx.respond = false // Bypass Koa's built-in response handling
      ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
      nuxt.render(ctx.req, ctx.res)
    }
    // ctx.body = {status: true, message: '测试数据'}
    next();
  })
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
